package com.can.Config;

import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

@Slf4j
@Configuration
public class ElasticsearchConfig {

    @Value("${spring.elasticsearch.uris:http://localhost:9200}")
    private String serverUrl;

    private RestClient restClient;

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        // 1. 创建低级客户端
        this.restClient = RestClient.builder( // 赋值给实例变量
            HttpHost.create(serverUrl)
        ).build();

        // 2. 创建JSON转换器
        ElasticsearchTransport transport = new RestClientTransport(
            restClient,
            new JacksonJsonpMapper()
        );

        // 3. 创建正式客户端
        return new ElasticsearchClient(transport);
    }

    @PreDestroy
    public void cleanup() {
        try {
            if (restClient != null) {
                restClient.close(); // 正确访问
                log.info("Elasticsearch client closed successfully");
            }
        } catch (IOException e) {
            log.error("Elasticsearch client close error", e);
        }
    }
}